<template>
  <div class="profile-container page-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人中心</h2>
        </div>
      </template>
      
      <div v-if="userStore.loading" class="loading">
        <el-skeleton :rows="4" animated />
      </div>
      
      <div v-else>
        <el-form 
          :model="userForm" 
          :rules="rules" 
          ref="userFormRef" 
          label-position="top"
          @submit.prevent="handleSubmit"
        >
          <el-form-item label="用户名" prop="username">
            <el-input 
              v-model="userForm.username" 
              placeholder="请输入用户名" 
            />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input 
              v-model="userForm.email" 
              placeholder="请输入邮箱" 
              disabled
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="password">
            <el-input 
              v-model="userForm.password" 
              placeholder="不修改请留空" 
              type="password" 
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="userForm.confirmPassword" 
              placeholder="不修改请留空" 
              type="password" 
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" native-type="submit" :loading="submitting" class="submit-btn">
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store/user'

// 路由
const router = useRouter()

// 用户状态管理
const userStore = useUserStore()

// 用户表单引用
const userFormRef = ref(null)

// 提交状态
const submitting = ref(false)

// 用户表单数据
const userForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 验证密码是否匹配
const validateConfirmPassword = (rule, value, callback) => {
  if (!value && !userForm.password) {
    // 如果都为空，表示不修改密码
    callback()
  } else if (!value && userForm.password) {
    callback(new Error('请确认新密码'))
  } else if (value !== userForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3至20个字符之间', trigger: 'blur' }
  ],
  password: [
    { min: 8, message: '密码长度不能小于8个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 初始化数据
onMounted(async () => {
  // 确保用户已登录
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  // 获取最新的用户数据
  try {
    await userStore.fetchUserInfo()
    
    // 设置表单初始值
    userForm.username = userStore.user.username
    userForm.email = userStore.user.email
    userForm.password = ''
    userForm.confirmPassword = ''
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
})

// 处理表单提交
const handleSubmit = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    submitting.value = true
    
    try {
      const updateData = {
        username: userForm.username
      }
      
      // 如果设置了新密码，添加到更新数据中
      if (userForm.password) {
        updateData.password = userForm.password
      }
      
      // 调用API更新用户信息
      await userStore.updateUser(updateData)
      
      // 如果更新了密码，提示用户并跳转到登录页面
      if (userForm.password) {
        ElMessage.success('密码已更新，请重新登录')
        await userStore.logout()
        router.push('/login')
      } else {
        ElMessage.success('个人信息更新成功')
        
        // 清空密码字段
        userForm.password = ''
        userForm.confirmPassword = ''
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '更新失败，请稍后重试')
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
.profile-container {
  display: flex;
  justify-content: center;
  padding-top: 30px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.profile-card {
  width: 100%;
  max-width: 500px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: center;
}

.card-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.loading {
  padding: 20px 0;
}

.submit-btn {
  width: 100%;
}
</style> 